import api from '@doctorwork/utils/network';
import { effects } from 'dva-core/saga';
import { cookie } from '../utils/common';
import endpoints from '../endpoints.js';
import sensor from '../../utils/sa';

// @TODO: 独立以下依赖
import { appName, WEAPP_VERSION, env } from '../api';

const isHybrid = false;

export const commonHeader = {
    token: '',
    userId: '',
    channel: 'h5',
    channelCode: '',
    device: 'h5',
    come_from: '',
    platformId: '1',
    appName,
};

export const HTTP_STATUS = {
    SUCCESS: 200,
    CLIENT_ERROR: 400,
    AUTHENTICATE: 401,
    FORBIDDEN: 403,
    NOT_FOUND: 404,
    SERVER_ERROR: 500,
    BAD_GATEWAY: 502,
    SERVICE_UNAVAILABLE: 503,
    GATEWAY_TIMEOUT: 504
};

export const API_STATUS = {
    SUCCESS: 0,
    AUTHENTICATE: 401
};

const  getWeAppUrl = (url) => {
    if (url.indexOf('http') === 0) return url;
    const reg = /\/([^\/]*)\//;
    const type_ = url.match(reg)[1];
    return url.replace(reg, endpoints[type_] + '/');
};

/**
 * 根据storage 保存的 trace 信息初始化header
 */
function initialHeader(trace) {
    if (!trace) return {};

    let header = {};
    trace.split(',').forEach(elm => {
        const [key, value] = elm.split(':');
        header[key] = value;
    });
    return header;
}


function* request(payload) {
    const { params, data = {}, option, method } = payload;
    // 删除空字段
    Object.keys(data).forEach(key => {
        if (data[key] == undefined) delete data[key];
    });

    // @BADCODE 不用每次请求都获取token
    const authToken = isHybrid
        ? ''
        : yield effects.put.resolve({
            type: '$storage/get',
            payload: 'token'
        });

    const defaultOption = {
        method: method,
        header: {
            // credentials: 'include',
            'Content-Type': 'application/json; charset=UTF-8',
            token: authToken,
            version : WEAPP_VERSION,
            timestamp: new Date().getTime()
        }
        // hybrid请求时覆盖默认配置
        // headers: commonHeader
    };
    const options = Object.assign(defaultOption, option);

    // 跳转健康终端小程序使用心选-head数据
    // @FIXME: 不应该是每次请求都需要调用？
    cookie.set('_head', options.header);
    let res = yield api(payload.url, data, params, options);
    let statusCode = res.statusCode || res.status;
    const { code, status } = res.data  ;

    // @TODO: 网络错误码处理, 拆分平台
    if (statusCode != HTTP_STATUS.SUCCESS) {
        yield effects.put({
            type: '$error/other',
            payload: { errmsg: '系统异常,请稍后再试' }
        });
        return Promise.reject(res.data);
    }
    if (code == API_STATUS.SUCCESS || status==API_STATUS.SUCCESS) {
        return Promise.resolve(res.data.data || res.data.result);
    } else if (code == API_STATUS.AUTHENTICATE) {
        yield effects.put({ type: '$error/auth', payload: res.data });
    } else {
        console.log('[error]:',res.data );
        // 上报用户登录天数
        try{
            sensor.track('http_error',{
                $element_type: JSON.stringify(payload.url),
                $element_content: JSON.stringify(data),
                $element_name : JSON.stringify(res.data && res.data.msg)
            });
        }catch(e){
            console.log('上报失败');
        }
        yield effects.put({ type: '$error/other', payload: res.data });
    }
    return Promise.reject(res.data);
}

export default {
    namespace: '$request',
    state: {
        domain: {},
        authToken: '',
        appName: ''
    },
    effects: {
        *get({ payload }) {
            payload.url = getWeAppUrl(payload.url);
            return yield request({ ...payload, method: 'GET' });
        },
        *post({ payload }) {
            payload.url = getWeAppUrl(payload.url);
            return yield request({ ...payload, method: 'POST' });
        },
        *pipe() {}
    }
};
